<?php
require_once SITE_ROOT_PATH.'/_lib/classes/class.supplier.php';
require_once SITE_ROOT_PATH.'/_lib/base/curl_multirequest.php';
require_once SITE_ROOT_PATH.'/_lib/classes/class.hotels.php';

class hotel_suppliers {

    protected $suppliers = array();
    protected $results   = array();

    public function __construct() {
        // load suppliers config details from file
        $xo = simplexml_load_file(SUPPLIERS_CONFIG_FILE, 'SimpleXMLElement', LIBXML_NOCDATA);
       // print_r($xo);
        if ($xo) {
            foreach ($xo as $supplier) {
                $asupplier = new supplier($supplier);
                $this->suppliers[$asupplier->get_id()] = $asupplier;
            }
        }    
    }

    public function hotel_search($form_params) {
        $search_queries = array();
        // build search queries for all suppliers
        foreach ($this->suppliers as $supplier) {
            $search_queries[$supplier->get_id()] = $supplier->build_search_query($form_params);
        }
        $results = $this->execute_search($search_queries);
///echo "here"; echo($results); die;

        // process results
        // transform result XMLs to native XML result format
        $xp = new XsltProcessor();
        // create a DOM document and load the XML datat
        $xml_doc = new DomDocument;
        // create a DOM document and load the XSL stylesheet
        $xsl = new DomDocument;
        // native results storage
        $native = array();
        foreach ($results as $supplier=>$result) {
            $xsl->load($this->suppliers[$supplier]->get_xslt_path("search"));
            // import the XSL styelsheet into the XSLT process
            $xp->importStylesheet($xsl);      
            if (@$xml_doc->loadXML($result)) {
                $native[$supplier] = $xp->transformToXml($xml_doc);
            } else {
                // signal error
                $GLOBALS['note'] = array('type'=>'neg', 'message'=>'System error occured. Please do another search. If error repeats, please contact site\'s administration');
                $this->log_error($supplier, $search_queries[$supplier]."\n\n".$result);
                $native[$supplier] = "";
            }
        }
        // free objects
        $xsl = null;
        $xml_doc = null;
        $xp = null;
        $results = null;
        $results = array();
        $results["hotels"] = array();
        $results["rooms_count"] = intval($form_params["no_rooms"]);
        $results["nights"] = intval($form_params["nights"]);
        $results["arrival_date"] = $form_params["arrival_date"];
        // process native XMLs, build associative arrays with data from them and merge all suppliers' hotels
        foreach ($native as $supplier=>$xml) {
            $xo = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
            // process results if present
            if ($xo && isset($xo->session)) {
                $session_id = trim($xo->session->id);
                $currency = trim($xo->session->Currency);
                foreach ($xo->session->Hotel as $value) {
                    $hotel = (array)$value;
                    $rooms = $hotel["Rooms"];
                    unset($hotel["Rooms"]);
                    $hotel["session_id"] = $session_id;
                    $hotel["currency"] = $currency;
                    $hotel["supplier_code"] = $supplier;
                    if (isset($rooms->Room_1)) {
                        $hotel["room_sets"][1]["adults"] = intval($rooms->Room_1->Passengers->Adults);
                        $hotel["room_sets"][1]["children"] = intval($rooms->Room_1->Passengers->Children);
                        foreach ($rooms->Room_1->Room as $room) {
                            $hotel["room_sets"][1]["rooms"][(string)$room->ID] = (array)$room;
                        }
                    }
                    if (isset($rooms->Room_2)) {
                        $hotel["room_sets"][2]["adults"] = intval($rooms->Room_2->Passengers->Adults);
                        $hotel["room_sets"][2]["children"] = intval($rooms->Room_2->Passengers->Children);
                        foreach ($rooms->Room_2->Room as $room) {
                            $hotel["room_sets"][2]["rooms"][(string)$room->ID] = (array)$room;
                        }
                    }
                    if (isset($rooms->Room_3)) {
                        $hotel["room_sets"][3]["adults"] = intval($rooms->Room_3->Passengers->Adults);
                        $hotel["room_sets"][3]["children"] = intval($rooms->Room_3->Passengers->Children);
                        foreach ($rooms->Room_3->Room as $room) {
                            $hotel["room_sets"][3]["rooms"][(string)$room->ID] = (array)$room;
                        }
                    }
                    $hotel["facility"] = (string)$hotel["facility"];
                    $results["hotels"][] = $hotel;
                }
            }
        }
        return $results;
    }

    public function hotel_map($data) {
        $hotels = array();
        $h = new hotels();
        foreach ($data["hotels"] as $hotel) {
            $hotel_values = $h->lookup_hotel($hotel);
            // If found add to array
            if ($hotel_values) {
                $hotels[$hotel_values["extra"]["hotel_id"]] = $hotel_values;
            } else {
                // Else flag as not found
                if (FEATURE_HOTEL_FLAGGING) {
                    $h->flag_hotel_instance($hotel);
                }
            }
        }
        $data["hotels"] = $hotels;
        return $data;
    }

public function set_results($results) {
$this->results = $results;
}

public function hotel_list($page) {
// TODO: implement pagination here
return $this->results;
}

public function hotel_book($data) {
$result = $this->suppliers[$data["supplier_code"]]->hotel_book($data);
$result["supplier_code"] = $data["supplier_code"];
return $result;
}

public function cancel_booking($data) {
$result = $this->suppliers[$data["supplier_code"]]->cancel_booking($data);
$result["supplier_code"] = $data["supplier_code"];
return $result;
}

public function get($id) {
if(isset($this->suppliers[$id])) {
return $this->suppliers[$id];
}
else return null;
}

protected function execute_search($queries) {
// quick cache for 1 supplier "youtravel" case
if(count($queries)==1 && isset($queries["you"])) {
$hash = md5($queries["you"]);
if(isset($_SESSION[$hash])) {
$result = $_SESSION[$hash];
}
else {
$result = curl_multirequest($queries);
$_SESSION[$hash] = $result;
}
return $result;
}
else {
$result = curl_multirequest($queries);
return $result;
}
}  

protected function log_error($supplier, $message) {
file_put_contents("logs/errors/".$supplier."-".date("Ymd-His"), $message);
}





  public function preprocess_search_form($params) {
    $day = $params["date_day"];
    $month = substr($params["date_month"],0,2);
    $year = substr($params["date_month"],5,2);
    $params["arrival_date"] = strtotime("$month/$day/$year");    

    // make a reference param for lowcostgroup
    //$params['AgentReference'] = 'IRELAND';
    // convert destination_tree_id to destination_id for supplier
    $tree = new tree();
    $aparams = array('tree_id' => $params["destination_tree_id"]);
    $destination_values = $tree->get_branch($aparams, '1');

    $destination_values = $destination_values[0];

    $dest_param_name = "youtravel_id";
    $dest = $destination_values["youtravel_id"];
    if (strpos($dest,"=")>0) {
        $pair = explode("=", $dest);
        // add part before "=" to param name
        // part after "=" become value
        $dest_param_name.="_".$pair[0];
        $dest = $pair[1];
    }
    $params[$dest_param_name] = $dest;
        if ($destination_values['regionID']) {$params['lowcostbeds_regionID'] = $destination_values['regionID'];}
    return $params;
}




}
